<template>
  <div class="speech-recognition">
    <button @click="startRecognition" :disabled="isRecognizing">开始录音</button>
    <button @click="stopRecognition" :disabled="!isRecognizing">停止录音</button>

    <div class="result">
      <h3>识别结果：</h3>
      <p>{{ text }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: '',
      isRecognizing: false,
      recognition: null
    }
  },
  mounted() {
    // 检查浏览器是否支持 Web Speech API
    if (!('SpeechRecognition' in window) && !('webkitSpeechRecognition' in window)) {
      alert('您的浏览器不支持语音识别功能，请使用 Chrome 或 Edge 浏览器');
      return;
    }

    // 初始化语音识别对象
    this.recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
    this.recognition.lang = 'zh-CN'; // 设置语言为中文
    this.recognition.interimResults = false; // 是否返回中间结果
    this.recognition.continuous = false; // 是否连续识别

    // 监听识别结果
    this.recognition.onresult = (event) => {
      const transcript = event.results[0][0].transcript;
      this.text = transcript;

      // 如果需要将结果发送到后端，可以在这里调用API
      // this.sendToBackend(transcript);
    };

    // 监听识别结束事件
    this.recognition.onend = () => {
      this.isRecognizing = false;
    };

    // 监听错误事件
    this.recognition.onerror = (event) => {
      console.error('语音识别错误:', event.error);
      alert(`语音识别出错: ${event.error}`);
      this.isRecognizing = false;
    };
  },
  methods: {
    startRecognition() {
      this.text = '';
      this.recognition.start();
      this.isRecognizing = true;
    },
    stopRecognition() {
      this.recognition.stop();
      this.isRecognizing = false;
    },
    sendToBackend(text) {
      // 这里可以调用后端API保存识别结果
      // 例如：
      // axios.post('/api/save-transcription', { text })
      //   .then(response => console.log('保存成功'))
      //   .catch(error => console.error('保存失败', error));
    }
  }
}
</script>

<style scoped>
.speech-recognition {
  margin: 20px;
}
.result {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>